<template>
  <div class="app-container">
    <!-- 卡片包裹内容 -->
    <el-card class="tree-card">
      <!-- 用el-row和el-col实现头部布局 -->
      <tree :nodescope="companyList" />
      <!-- 分隔符 -->
      <hr>
      <!-- 树状组件 -->
      <el-tree :data="depts" :props="{label:'name'}" default-expand-all>
        <!-- 用作用域插槽丰富组件内容 -->
        <template v-slot="scoped">
          <!-- 需要遍历的每一行都跟顶部布局一样，可以直接把顶部布局的内容给复制下来 -->
          <tree
            :nodescope="scoped.data"
            @isShowDialog="ShowDialog"
            @editDialog="editDialog"
            @reload="getDepts"
          />

        </template>

      </el-tree>

    </el-card>
    <!-- 弹出新增框 -->
    <add-depts
      :id="id"
      ref="addDialog"
      :is-show-dialog="isShowDialog"
      @resreload="getDepts"
      @closeDialog="isShowDialog=false"
    />
  </div>

</template>

<script>
import tree from './component/index.vue'
import { getDepts } from '@/api/departments'
import addDepts from '@/views/departments/component/addDepts.vue'
export default {
  components: { tree, addDepts },

  data() {
    return {
      isShowDialog: false,
      id: '',
      companyList:
      {
        name: '传智教育',
        manager: '负责人'
      },

      // 部门列表数据
      depts: []
    }
  },
  created() {
    this.getDepts()
  },
  methods: {
    // 监听点击新增部门事件，把isShowDialog改成true
    ShowDialog(id) {
      this.id = id
      this.isShowDialog = true
    },
    // 监听编辑事件，把isShowDialog改成true
    editDialog(id) {
      this.id = id
      this.$refs.addDialog.getShowDialog(id)
      this.isShowDialog = true
    },
    // 获取部门信息
    async getDepts() {
      const res = await getDepts()
      this.depts = this.listToTree(res.depts, '')
    },
    // 单独封装一个递归函数把一维数组处理成多维
    listToTree(list, id) {
      const res = []
      list.forEach(element => {
        if (element.pid === id) {
          element.children = this.listToTree(list, element.id)
          res.push(element)
        }
      })
      return res
    }

  }

}
</script>

<style scoped>
.tree-card {
  padding: 30px  140px;
  font-size:14px;
}

</style>
